package com.example.android427;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.SeekBar;

import androidx.appcompat.app.AppCompatActivity;

public class ShigeActivity extends AppCompatActivity {

    private SeekBar main_sb;
    private ImageButton main_ib;
    private MediaPlayer mediaplayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.shigebofang);

        //获取控件id
        main_sb = findViewById(R.id.main_sb);
        main_ib = findViewById(R.id.main_ib);

        //设置按钮初始图标
        main_ib.setImageResource(android.R.drawable.ic_media_play);
        main_ib.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //判断
                if (mediaplayer==null){
                    //放入歌曲
                    mediaplayer=MediaPlayer.create(ShigeActivity.this,R.raw.shige);
                    //设置进度条最大长度为音频时长
                    main_sb.setMax(mediaplayer.getDuration());
                    //开始播放
                    mediaplayer.start();
                    //使按钮变为暂停图标
                    main_ib.setImageResource(android.R.drawable.ic_media_pause);
                    //线程开始运行
                    new  myThread().start();
                }else if (mediaplayer.isPlaying()){
                    //如果正在播放 (暂停)
                    mediaplayer.pause();
                    //改变按钮为播放
                    main_ib.setImageResource(android.R.drawable.ic_media_play);
                }else{
                    //如果没有播放 (播放)
                    main_ib.setImageResource(android.R.drawable.ic_media_pause);
                }

            }
        });
        //设置进度条快进效果
        main_sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            //值改变
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            //值改变前
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            //值改变后
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mediaplayer.seekTo(main_sb.getProgress());
            }
        });


    }
    //设置一个线程运行进度条
    class  myThread extends Thread{
        @Override
        public void run() {
            super.run();
            //判断当前播放位置是否小于总时长
            while (main_sb.getProgress()<=main_sb.getMax()) {
                //设置进度条当前位置为音频播放位置
                main_sb.setProgress(mediaplayer.getCurrentPosition());
            }
        }
    }
}
